package com.campus.common;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;

@Component
public class JwtUtil {

    // 使用 Keys.secretKeyFor 方法生成符合 HS256 要求的密钥,动态生成
    private static final SecretKey SECRET_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS256);

    public static String generateToken(String username, Integer roleId) {
        return Jwts.builder()
                .setSubject(username)
                .claim("roleId", roleId)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 86400000)) // 1 天有效期
                .signWith(SECRET_KEY)
                .compact();
    }

    public static Claims validateToken(String token) {
        try {
            return Jwts.parserBuilder()
                    .setSigningKey(SECRET_KEY)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            e.printStackTrace(); // 添加异常处理以便调试
            return null;
        }
    }

    // 提取 roleId
    public static int extractRoleId(String token) {
        Claims claims = validateToken(token);
        return claims.get("roleId", Integer.class);  // 从 Token 中提取 roleId
    }

}

